package com.huaxindata.im.main.chathistory;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.huaxin.common.view.avatarimageview.AvatarImageView;
import com.huaxin.common.view.avatarimageview.HxAvatarImageGlide;
import com.huaxindata.im.R;
import com.huaxindata.im.constants.ImConstants;
import com.huaxindata.im.main.addFriend.AddFriendActivity;
import com.huaxindata.im.main.chat.ConversationActivity;
import com.huaxindata.im.main.chat.ConversationManager;
import com.huaxindata.im.main.contactview.friend.HxPersonalCenterActivity;
import com.huaxindata.im.main.contactview.group.SelectGroupMemberActivity;
import com.huaxindata.im.main.manager.ContactManager;
import com.huaxindata.im.main.manager.HistoryContactManager;
import com.huaxindata.im.main.manager.UserManager;
import com.huaxindata.im.main.menu.SearchContactActivity;
import com.huaxindata.im.model.contact.Contact;
import com.huaxindata.im.model.contact.ContactGroup;
import com.huaxindata.im.model.contact.ContactPerson;
import com.huaxindata.im.model.contact.ContactTmp;
import com.huaxindata.im.model.db.MessageStore;
import com.huaxindata.im.model.entity.ChatMessage;
import com.huaxindata.im.util.Log;
import com.huaxindata.im.view.SwipeLayout;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/8/16.
 * 用于展示消息聊天记录的类
 */

public class MessageFragment extends Fragment {

    private ImageView mAddIv;
    private Toolbar   mToolbar;
    private ListView  mListView;
    //没有消息记录时显示提示信息的textView
    private TextView  mEmptyMessageTv;

    private PopupWindow mPopupWindow;//用来显示弹出菜单
    private Context     mContext;

    private List<Contact>      mContactList;
    private MessageItemAdapter mAdapter;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        //onAttach(context)方法是在安卓23才加入的,
        //在低于23的机器上只能用onAttach(activity)
        //但是用兼容包里的不会有这个问题
        this.mContext = context;
    }

    /**
     * 从聊天记录中获取需要显示的历史联系人记录
     */
    public void initData() {
        mContactList = HistoryContactManager.getHistoryContactList();
        if (mContactList.size() == 0) {
            mEmptyMessageTv.setVisibility(View.VISIBLE);
        } else {
            mEmptyMessageTv.setVisibility(View.GONE);
        }
        //第一次进入页面时，adapter还没有初始化，故要判空
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle
            savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_message, container, false);
        initView(view);
        return view;
    }

    @Override
    public void onResume() {
        initData();
        super.onResume();
    }

    private void initView(View view) {
        mAddIv = (ImageView) view.findViewById(R.id.fragment_message_toolbar_add);
        mToolbar = (Toolbar) view.findViewById(R.id.fragment_message_toolbar);
        mListView = (ListView) view.findViewById(R.id.fragment_message_listView);
        mEmptyMessageTv = (TextView) view.findViewById(R.id.fragment_message_empty);
        initPopupWindowMenu();
        mAddIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopupWindowMenu();
            }
        });
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                SwipeLayout.shrinkAllView();
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            }
        });
        mAdapter = new MessageItemAdapter();
        mListView.setAdapter(mAdapter);
    }

    private void showPopupWindowMenu() {
        mPopupWindow.showAsDropDown(mAddIv, -20, 5, Gravity.LEFT);
    }

    private void initPopupWindowMenu() {
        View view = View.inflate(mContext, R.layout.toolbar_popwindow_menu, null);
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        mPopupWindow = new PopupWindow(view, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout
                .LayoutParams.WRAP_CONTENT, true);
        view.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    mPopupWindow.dismiss();
                    return true;
                }
                return false;
            }
        });
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (mPopupWindow != null && mPopupWindow.isShowing()) {
                    mPopupWindow.dismiss();
                    return true;
                }
                return false;
            }
        });
        View addFriends = view.findViewById(R.id.pop_menu_add);
        View qunliao = view.findViewById(R.id.pop_menu_qunliao);
        View scan = view.findViewById(R.id.tv_scan);
        addFriends.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopupWindow.dismiss();
                Intent intent = new Intent(mContext, SearchContactActivity.class);
                startActivity(intent);
            }
        });
        qunliao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopupWindow.dismiss();
                Intent intent = new Intent(mContext, SelectGroupMemberActivity.class);
                startActivity(intent);
            }
        });

        scan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent("action_huaxin_scancature");
                //设置 Intent 的动作为清单中指定的action
                intent.addCategory("action_huaxin_scancature");
                startActivityForResult(intent, 0);
                //   startActivityForResult(new Intent(getActivity(), ScanCaptureActivity.class), 0);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 0 && resultCode== Activity.RESULT_OK) {
            String dataString = data.getStringExtra("code");
            Log.e("lwjing","code "+dataString);
            if (dataString != null) {
                if (dataString.contains("#&")) {
                    String[] split = dataString.split("#&");
                    if (split.length == 6) {
                        //id  name 图片链接 手机号码
                        ContactPerson person = new ContactPerson(split[2], split[4], split[3], split[5], null, null);
                      /*  ContactInfoDialog dialog = new ContactInfoDialog(getContext());
                        dialog.show(person);*/
                        Intent intent = new Intent(getActivity(), HxPersonalCenterActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putParcelable("contact", person);
                        intent.putExtras(bundle);
                        getActivity().startActivity(intent);
                    }
                }else {
                    try {
                        String dataStr = data.getStringExtra("code");
                        JSONObject jsonObject = new JSONObject(dataStr);
                        String typeValue = (String) jsonObject.get("typeValue");
                        if (typeValue.equals("fre")) {
                            String nameID = (String) jsonObject.get("nameID");
                            String name = (String) jsonObject.get("name");
                            String phone = (String) jsonObject.get("phone");
                            String imgeUrl = (String) jsonObject.get("imgeUrl");
                            ContactPerson person = new ContactPerson(nameID, imgeUrl, name, phone, "", "");
                            Intent intent = new Intent(getActivity(), HxPersonalCenterActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putParcelable("contact", person);
                            intent.putExtras(bundle);
                            getActivity().startActivity(intent);
                        }
                    } catch (Exception e) {

                    }
                }
            }
        }
    }


    private class MessageItemAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mContactList == null ? 0 : mContactList.size();
        }

        @Override
        public Object getItem(int position) {
            return mContactList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final MsgViewHolder viewHolder;
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout
                        .fragment_message_item, parent, false);
                viewHolder = new MsgViewHolder(convertView);
                SwipeLayout.addSwipeView(viewHolder.swipeLayout);
            } else {
                viewHolder = (MsgViewHolder) convertView.getTag();
            }
            SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd HH:mm");
            final Contact contact = mContactList.get(position);
            //此处要分别显示不同的联系人的信息
            if (contact instanceof ContactTmp) {
                //new friend!
                ContactTmp contactTmp = (ContactTmp) contact;
                viewHolder.icon.setImageResource(R.mipmap.new_friend);
                viewHolder.iconExpand.setVisibility(View.GONE);
                viewHolder.name.setText("新的好友");
                ChatMessage message = HistoryContactManager.getRecentMessage(contactTmp.getClientId(), UserManager.getClientId());
                //可能出现在未添加好友之前有未读的聊天消息
                int count = HistoryContactManager.getUnReadCount(contactTmp.getClientId(), UserManager.getClientId());
                if (count > 0) {
                    viewHolder.unread.setText("" + count);
                    viewHolder.unread.setVisibility(View.VISIBLE);
                } else {
                    viewHolder.unread.setVisibility(View.GONE);
                }

                if (message != null) {
                    viewHolder.time.setText(dateFormat.format(new Date(message.timestamp)));
                }
                viewHolder.content.setText(contactTmp.getNickName() + "请求添加您为好友");

            } else if (contact instanceof ContactGroup) {//群联系人
                ContactGroup group = (ContactGroup) contact;
                //设置头像
                Glide.with(MessageFragment.this).load(group.getGroupIcon())
                        .apply(new RequestOptions().placeholder(R.mipmap.new_group)).into(viewHolder.icon);
                //setHeaderView(person.getIcon(),person.getNickName(), icon);

                ChatMessage message = HistoryContactManager.getRecentMessageFromGroup(group
                        .groupClientId);
                if (message != null) {
                    viewHolder.content.setText(message.getSimpleString());
                    viewHolder.time.setText(dateFormat.format(new Date(message.timestamp)));
                } else {
                    viewHolder.content.setText("加入群聊吧...");
                    viewHolder.time.setVisibility(View.GONE);
                }
                viewHolder.name.setText(group.getGroupName());
                int count = HistoryContactManager.getUnreadCountFromGroup(group.groupClientId);
                if (count > 0) {
                    viewHolder.unread.setText(count > 99 ? "99+" : "" + count);
                    viewHolder.unread.setVisibility(View.VISIBLE);
                } else {
                    viewHolder.unread.setVisibility(View.GONE);
                }
            } else if (contact instanceof ContactPerson) {//好友联系人
                ContactPerson person = (ContactPerson) contact;
                //设置头像
                //Glide.with(MessageFragment.this).load(person.getIcon()).into(viewHolder.icon);
                setHeaderView(person.getIcon(), person.getNickName(), viewHolder.icon);


                ChatMessage message = HistoryContactManager.getRecentMessage(person.getClientId(), UserManager.getClientId());
                if (message != null) {
                    viewHolder.content.setText(message.getSimpleString());//设置最近一条消息的内容
                    viewHolder.time.setText(dateFormat.format(new Date(message.timestamp)));
                } else {
                    viewHolder.content.setText("开始聊天吧...");
                    viewHolder.time.setVisibility(View.GONE);
                }
                viewHolder.name.setText(person.getNickName());//设置昵称
                int count = HistoryContactManager.getUnReadCount(person.getClientId(), UserManager.getClientId());
                if (count > 0) {
                    viewHolder.unread.setText(count > 99 ? "99+" : "" + count);
                    viewHolder.unread.setVisibility(View.VISIBLE);
                } else {
                    viewHolder.unread.setVisibility(View.GONE);
                }
            }
            viewHolder.mainContent.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    boolean isExpand = SwipeLayout.isExpand();
                    if (isExpand) {
                        SwipeLayout.shrinkAllView();
                    } else {
                        final Intent intent;
                        if (contact instanceof ContactTmp) {
                            intent = new Intent(mContext, AddFriendActivity.class);
                            intent.putExtra(ImConstants.CONTACT, contact);
                            intent.putExtra(ImConstants.FUNCTION_ADD_FRIEND, ImConstants
                                    .FUNCTION_RESPONSE);
                            //查询两人的所有系统消息，并将其置为已读
                            List<ChatMessage> sysMessage = MessageStore.querySysByClientId(contact.clientId,
                                    UserManager.getClientId());
                            for (ChatMessage message : sysMessage) {
                                if (message.read == 0) {
                                    message.read = 1;
                                    MessageStore.updateReadingState(message.timestamp, message.sender, 1);
                                }
                            }


                        } else {
                            intent = new Intent(mContext, ConversationActivity.class);
                            if (contact instanceof ContactPerson) {
                                Contact tmp = ContactManager.getContactById(contact.getClientId());//如果网络数据没下载下来则用缓存的
                                ConversationManager.setChatObject(tmp == null ? contact : tmp);
                            } else if (contact instanceof ContactGroup) {
                                Contact tmp = ContactManager.getGroupById(contact
                                        .getClientId());
                                ConversationManager.setChatObject(tmp == null ? contact : tmp);
                            }
                        }
                        startActivity(intent);
                    }
                }
            });
            //滑动删除联系人记录，但是消息记录还在，并没有删除
            viewHolder.delete_message.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //此处为更新数据库使消息不再显示
                    HistoryContactManager.hideChatHistory(contact.getClientId());
                    //更新群消息状态，将所有未读消息置为已读
                    if (contact instanceof ContactGroup) {
                        MessageStore.updateReadingStateFromGroup(contact.getClientId());
                    } else if (contact instanceof ContactPerson) {
                        MessageStore.updateReadingState(contact.getClientId());
                    }
                    //TODO 更新主页未读数
                    FragmentActivity activity = getActivity();
                    initData();
                    SwipeLayout.removeSwipeView(viewHolder.swipeLayout);
                }
            });
            return convertView;
        }
    }

    /**
     * 设置头像
     *
     * @param userimg
     * @param nickname
     * @param imageView
     */
    private void setHeaderView(String userimg, String nickname, AvatarImageView imageView) {
        HxAvatarImageGlide instance = HxAvatarImageGlide.getInstance();
        instance.setHeadImage(mContext, userimg, nickname, imageView);
    }

    private class MsgViewHolder {
        //头像
        public AvatarImageView icon;
        //名称
        public TextView        name;
        //名称特殊标识
        public ImageView       nameIv;
        //显示最近一条消息发送时间
        public TextView        time;
        //最近一条消息发送内容
        public TextView        content;
        //显示未读消息数
        public TextView        unread;
        public TextView        iconExpand;

        public SwipeLayout swipeLayout;
        public View        mainContent;//消息item的容器
        public View        delete_message;//消息的删除按钮

        public MsgViewHolder(View view) {
            super();
            icon = (AvatarImageView) view.findViewById(R.id.iv_icon);
            name = (TextView) view.findViewById(R.id.tv_name);
            nameIv = (ImageView) view.findViewById(R.id.iv_name);
            time = (TextView) view.findViewById(R.id.tv_time);
            content = (TextView) view.findViewById(R.id.tv_content);
            unread = (TextView) view.findViewById(R.id.tv_unread);
            iconExpand = (TextView) view.findViewById(R.id.iv_icon_expand);
            mainContent = view.findViewById(R.id.left_content_view);
            delete_message = view.findViewById(R.id.delete_message);
            swipeLayout = (SwipeLayout) view.findViewById(R.id.message_item_swipeLayout);
            view.setTag(this);
        }
    }
}
